package com.product.interceptor;


import com.alibaba.fastjson.JSON;
import com.product.enmu.HttpStatusEnum;
import com.product.entity.Users;
import com.product.result.ApiResult;
import com.product.service.IUsersService;
import com.product.utils.JwtUtil;
import com.product.utils.ThreadLocalUtils;
import com.product.vo.UserVo;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;

@Component
public class JwtInterceptor implements HandlerInterceptor {
    @Autowired
    private JwtUtil jwtUtils;
    @Autowired
    private IUsersService userService;

    @Override
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        String token = request.getHeader("Authorization");
        if (token != null) {
            try {
                String username = jwtUtils.parseToken(token, UserVo.class).getUsername();
                Users user = userService.lambdaQuery().eq(Users::getUsername, username).one();
                UserVo userVo = new UserVo();
                BeanUtils.copyProperties(user, userVo);
                // 把业务数据存储到ThreadLocal（ThreadLocal 线程安全，能实现数据共享）
                ThreadLocalUtils.set(userVo);
                return true;
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        response.setContentType("application/json;charset=utf-8");
        response.getWriter().write(JSON.toJSONString(ApiResult.getResult(null, HttpStatusEnum.UNAUTHORIZED.getCode(), "Token无效，请重新登录")));
        return false;
    }

    @Override
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {
        ThreadLocalUtils.remove();
    }
}
